package org.cloudnote.service.impl;

import org.cloudnote.bean.User;
import org.cloudnote.mapper.UserMapper;
import org.cloudnote.service.UserService;
import org.cloudnote.util.NoteUtil;
import org.cloudnote.bean.NoteResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;


    @Override
    public NoteResult login(String username, String password) {
        User user = userMapper.getByName(username);
        NoteResult result = new NoteResult();
        if (user == null) {
            result.setStatus(1);
            result.setMsg("用户名不存在");
            return result;
        }
        String truepwd = user.getPassword();
        String s = NoteUtil.md5(password);
        if(!s.equals(truepwd)){
            result.setStatus(2);
            result.setMsg("密码错误");
            return result;
        }
        result.setStatus(0);
        result.setMsg("登录成功");
        result.setData(user);
        return result;
    }

    @Override
    public NoteResult register(User user) {
        NoteResult result = new NoteResult();
        User u = new User();
        User has_user = userMapper.getByName(user.getUsername());//先判断用户名是否存在
        if(has_user != null){
            result.setStatus(1);
            result.setMsg("用户名已存在");
            return result;
        }
        u.setUsername(user.getUsername());
        u.setPassword(NoteUtil.md5(user.getPassword()));
        u.setToken(null);
        u.setId(NoteUtil.createId());
        userMapper.register(u);
        result.setStatus(0);
        result.setMsg("注册成功");
        result.setData(u);
        return result;
    }
}
